package com.yuewi.consumer;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.yuwei.common.model.User;
import com.yuwei.common.service.UserService;
import com.yuwei.yurpc.model.RpcRequest;
import com.yuwei.yurpc.model.RpcResponse;
import com.yuwei.yurpc.serializer.JdkSerializer;
import com.yuwei.yurpc.serializer.Serializer;

/**
 * 静态代理
 *
 * @author yuwei
 * @date 16:37 2024/10/3
 */
public class UserServiceProxy implements UserService {
    @Override
    public User getUser(User user) {
        //指定序列化器
        Serializer serializer = new JdkSerializer();
        RpcRequest request = new RpcRequest(UserService.class.getName(),"getUser", new Class[]{User.class}, new Object[]{user});
        try{
            byte[] body  = serializer.serialize(request);
            byte[] result = null;
            try(HttpResponse response = HttpRequest.post("http://localhost:8888").body(body).execute()){
                result = response.bodyBytes();
            }
            RpcResponse rpcResponse = (RpcResponse)serializer.deserialize(result,RpcResponse.class);
            return (User)rpcResponse.getData();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
